package com.gljx.web.controller;

import com.gljx.constant.ActivitiKey;
import com.gljx.util.*;
import com.gljx.web.Entity.*;
import com.gljx.web.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.lang.reflect.Array;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author lcx
 * @Date 2017/12/14 0014 上午 8:45
 */
@Controller
@RequestMapping("/")
public class CarmainTainContraller {
    @Autowired
    DepartmentService departmentService;
    @Autowired
    CustomLogService customLogService;
    @Autowired
    CarmainTainService carmainTainService;
    @Autowired
    PersonController personController;
    @Autowired
    CarService carService;

    @Autowired
    RepairShopService repairShopService;

    private ImportExecl poi = new ImportExecl();//创建poi工具类
    /**
     * @Author lcx
     * @Date 2018/2/7 0007 上午 9:19
     * 查询车辆维修
     */
    @RequestMapping("/queryCarmaintain/look.action")
    public String queryCarmaintain(HttpServletRequest request, @RequestParam(value = "fnumber", defaultValue = "") String fnumber
            , @RequestParam(value = "cfcoachno", defaultValue = "") String cfcoachno
            , @RequestParam(value = "jlName", defaultValue = "") String jlName
            , @RequestParam(value = "beginTime", defaultValue = "") String beginTime
            , @RequestParam(value = "endTime", defaultValue = "") String endTime
            , @RequestParam(value = "state", defaultValue = "") String state
            , @RequestParam(value = "alertType", defaultValue = "") String alertType
            , @RequestParam(value = "departmentid", defaultValue = "") String departmentid
            , @RequestParam(value = "cfmaintetype", defaultValue = "") String cfmaintetype
            , @RequestParam(value = "repairshopid", defaultValue = "") String repairshopid
            , @RequestParam(value = "carNumber", defaultValue = "") String carNumber) {

        PageBean<Carmaintain> pb = new PageBean<>();
        //获取操作人信息
        User user = (User) request.getSession().getAttribute("user");
        try {
            fnumber = fnumber.trim();//去空格
            cfcoachno = cfcoachno.trim();
            jlName = jlName.trim();
            //第一次进来
            if ("first".equals(state)) {
                beginTime = TimeFormat.getMonth();
                endTime = TimeFormat.getNowTime();
                pb = getPageBean(request, user.getFcompanyid(), fnumber, cfcoachno, jlName, departmentid,cfmaintetype, beginTime, endTime, "",repairshopid,carNumber.trim());
            } else if ("".equals(state) && "".equals(beginTime) || "".equals(endTime)) {
                pb = getPageBean(request, user.getFcompanyid(), fnumber, cfcoachno, jlName, departmentid,cfmaintetype,beginTime, endTime, null,repairshopid,carNumber.trim());
            } else {
                //获取分页  如果编码为空默认按照业务日期排序分页显示
                pb = getPageBean(request, user.getFcompanyid(), fnumber, cfcoachno, jlName, departmentid,cfmaintetype, beginTime, endTime, "",repairshopid,carNumber.trim());
            }
            //计数器
            int i = 0;
            //缓存需要删除的序列
            List<Integer> tem = new ArrayList<>();
            //获取当前分页的值
            List<Carmaintain> CarmaintainList = pb.getBeanList();
            List<Carmaintain> CarmaintainListNew = new ArrayList<>();

            for(Carmaintain carmaintain:CarmaintainList){
               if("".equals(carmaintain.getCfbasemanhours())||carmaintain.getCfbasemanhours()==null){
                   carmaintain.setCfbasemanhours(new BigDecimal(0.00));
               }
               if("".equals(carmaintain.getCfamount())||carmaintain.getCfamount()==null){
                   carmaintain.setCfamount(new BigDecimal(0.00));
               }
                CarmaintainListNew.add(carmaintain);
            }

            List<Department> departmentList = departmentService.selectAdminListAsfcontid("", user.getFcompanyid());

            List<RepairShop> repairShopList= repairShopService.queryRepairShopAll();
            //合计信息总条数
            String messageAmount="共有"+pb.getTr()+"条信息";
            //把数据传到页面
            request.setAttribute("messageAmount",messageAmount);
            request.setAttribute("fnumber", fnumber);
            request.setAttribute("cfcoachno", cfcoachno);
            request.setAttribute("jlName", jlName);
            request.setAttribute("beginTime", beginTime);
            request.setAttribute("endTime", endTime);
            request.setAttribute("departmentid", departmentid);
            request.setAttribute("cfmaintetype", cfmaintetype);
            request.setAttribute("repairshopid",repairshopid);//修理厂id
            request.setAttribute("carNumber",carNumber);//车牌号码
            request.setAttribute("CarmaintainList", CarmaintainListNew);
            request.setAttribute("DepartmentList", departmentList);
            request.setAttribute("RepairShopList",repairShopList);
            request.setAttribute("pb", pb);
            request.setAttribute("alertType", alertType);
            request.setAttribute("activitiBPMN_KEY", ActivitiKey.Driving_GL_ID.equals(user.getFcompanyid())
                    ? ActivitiKey.CLWX_KEY_GL
                    : ActivitiKey.CLWX_KEY_NC);


        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return "/backHome/carManagement/carmainTain/CarmainTainList";
    }

    /**
     * @Author lcx
     * @Date 2018/2/7 0007 上午 9:19
     * 列表的分页
     */
    public PageBean<Carmaintain> getPageBean(HttpServletRequest request, String companyId, String fnumber,
                                             String cfcoachno, String jlName, String departmentid,String cfmaintetype,
                                             String beginTime, String endTime,
                                             String state,String repairshopid,String carNumber) throws Exception {

        int offset;//从第几条数据开始加载
        if (request.getParameter("pager.offset") == null) {
            offset = 0;
        } else {
            offset = Integer.parseInt(request.getParameter("pager.offset"));
        }
        //拼接SQL语句
        StringBuffer psql = new StringBuffer();
        if (state == null) {
            psql.append("SELECT " +
                    "  c.fid, " +
                    "  c.FNUMBER, " +
                    "  to_char(c.FBIZDATE, 'YYYY-MM-DD') fbizdate, " +
                    "  c.FDESCRIPTION, " +
                    "  u.NAME                            createName, " +
                    "  u2.NAME                           checkName, " +
                    " " +
                    "  m.FNAME_L2 cfmaintainitemName, " +
                    "  c2.CFBASEMANHOURS, " +
                    "  c2.CFPRICE, " +
                    "  c2.CFQTY, " +
                    "  c2.cfmanhours,"+
                    "  c2.CFAMOUNT, " +
                    "  c.CFBILLSTATE, " +
                    "  ca.FNUMBER cfcarName, " +
                    "  c2.CFREMARK, " +
                    "  c2.CFALLAMOUNT, " +
                    "  c2.CFGSQTY, " +
                    "  a.FNAME_L2 cfdepartmentName, " +
                    "  c.CFMAINTETYPE, " +
                    "  p.FNAME_L2 jlName, " +
                    "  r.FNAME_L2 cfrepairshopName," +
                    "   c.FCREATETIME " +
                    "FROM ct_ds_carmaintain c LEFT JOIN ct_ds_carmaintainentry c2 ON c.fid = c2.FPARENTID " +
                    "  LEFT JOIN T_E_USER u ON c.FCREATORID = u.FID " +
                    "  LEFT JOIN T_E_USER u2 ON c.FAUDITORID = u2.fid " +
                    " LEFT JOIN ct_ds_maintainitem m on c2.CFMAINTAINITEMID = m.fid " +
                    "LEFT JOIN CT_DS_CAR ca on ca.fid = c.CFCARID " +
                    "  LEFT JOIN CT_DS_ADMIN a on c.CFDEPARTMENTID = a.FID " +
                    "LEFT JOIN CT_DS_PERSON p on p.fid = c.CFJIAOLIANID " +
                    "  LEFT JOIN ct_ds_repairshop r on c2.CFREPAIRSHOPID = r.FID");
            psql.append(" where c.FCONTROLUNITID= '" + companyId + "' ");
            if (!"".equals(cfmaintetype)) {
                if("4".equals(cfmaintetype)){
                    psql.append("and c.cfmaintetype = '" + 2 + "' ");
                }else{
                psql.append("and c.cfmaintetype = '" + cfmaintetype + "' ");
                }
            }
            if (!"".equals(jlName)) {
                psql.append("and p.FNAME_L2 LIKE '%" + jlName + "%' ");
            }
            if (!"".equals(departmentid)) {
                psql.append("and a.fid ='" + departmentid + "' ");
            }
            if (!"".equals(cfcoachno)) {
                psql.append(" AND m.FNAME_L2 LIKE '%" + cfcoachno + "%' ");
            }
            if(!"".equals(repairshopid)){
                psql.append("and r.fid ='" + repairshopid + "' ");
            }
            if(!"".equals(carNumber)){
                psql.append("and ca.FNUMBER LIKE '%" + carNumber + "%' ");
            }

            psql.append(" ORDER BY c.FCREATETIME DESC");
        } else {
            psql.append("SELECT " +
                    "  c.fid, " +
                    "  c.FNUMBER, " +
                    "  to_char(c.FBIZDATE, 'YYYY-MM-DD') fbizdate, " +
                    "  c.FDESCRIPTION, " +
                    "  u.NAME                            createName, " +
                    "  u2.NAME                           checkName, " +
                    " " +
                    "  m.FNAME_L2 cfmaintainitemName, " +
                    "  c2.CFBASEMANHOURS, " +
                    "  c2.CFPRICE, " +
                    "  c2.CFQTY, " +
                    "  c2.cfmanhours,"+
                    "  c2.CFAMOUNT, " +
                    "  c.CFBILLSTATE, " +
                    "  ca.FNUMBER cfcarName, " +
                    "  c2.CFREMARK, " +
                    "  c2.CFALLAMOUNT, " +
                    "  c2.CFGSQTY, " +
                    "  a.FNAME_L2 cfdepartmentName, " +
                    "  c.CFMAINTETYPE, " +
                    "  p.FNAME_L2 jlName, " +
                    "  r.FNAME_L2 cfrepairshopName," +
                    "   c.FCREATETIME " +
                    "FROM ct_ds_carmaintain c LEFT JOIN ct_ds_carmaintainentry c2 ON c.fid = c2.FPARENTID " +
                    "  LEFT JOIN T_E_USER u ON c.FCREATORID = u.FID " +
                    "  LEFT JOIN T_E_USER u2 ON c.FAUDITORID = u2.fid " +
                    " LEFT JOIN ct_ds_maintainitem m on c2.CFMAINTAINITEMID = m.fid " +
                    "LEFT JOIN CT_DS_CAR ca on ca.fid = c.CFCARID " +
                    "  LEFT JOIN CT_DS_ADMIN a on c.CFDEPARTMENTID = a.FID " +
                    "LEFT JOIN CT_DS_PERSON p on p.fid = c.CFJIAOLIANID " +
                    "  LEFT JOIN ct_ds_repairshop r on c2.CFREPAIRSHOPID = r.FID");
            psql.append(" where c.FCONTROLUNITID= '" + companyId + "' ");
            if (!"".equals(cfmaintetype)) {
                if("4".equals(cfmaintetype)){
                psql.append("and c.cfmaintetype = '" + 2 + "' ");
                }else{

                psql.append("and c.cfmaintetype = '" + cfmaintetype + "' ");
                }
            }
            if (!"".equals(jlName)) {
                psql.append("and p.FNAME_L2 LIKE '%" + jlName + "%' ");
            }
            if (!"".equals(departmentid)) {
                psql.append("and a.fid ='" + departmentid + "' ");
            }
            if (!"".equals(cfcoachno)) {
                psql.append(" AND m.FNAME_L2 LIKE '%" + cfcoachno + "%' ");
            }
            if(!"".equals(repairshopid)){
                psql.append("and r.fid ='" + repairshopid + "' ");
            }

            psql.append(" AND (c.FBIZDATE BETWEEN to_date('" + beginTime + "', 'YYYY/MM/DD') AND to_date('" + endTime + "', 'YYYY/MM/DD'))" +
                    "  ORDER BY c.FBIZDATE,c.fnumber DESC");
        }
//        a.fnumber,c.FBIZDATE,c.fnumber
        int psize = 200; //每页显示数
        int pindex = offset / psize;//+1  页码从0开始
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap = carmainTainService.selectPage(pindex, psql.toString(), psize);
        PageBean<Carmaintain> pb = new PageBean<>();
        pb.setPc(pindex); //页码
        Map<String, Object> paramMapCount = getPageBeanCount(psql.toString()); //取记录总数
        pb.setTr((int) paramMapCount.get("Pcount")); //记录总数
        pb.setPs(psize);
        pb.setBeanList((List<Carmaintain>) paramMap.get("v_cur")); //每页数据集
        return pb;
    }

    /**
     * @Author lcx
     * @Date 2017/12/15 0015 上午 9:47
     */
    public Map<String, Object> getPageBeanCount(String psql) throws Exception {

        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap = carmainTainService.selectPageCount(psql);
        return paramMap;
    }

    /**
     * @Author lcx
     * @Date 2018/2/7 0007 上午 9:19
     * 跳转到添加页面
     */
    @RequestMapping(value = "/go_add_Carmaintain")
    public String goAddCarmaintain(HttpServletRequest request, String alertType) throws Exception {
        //获取操作人信息
        User user = (User) request.getSession().getAttribute("user");
        Department department = departmentService.queryAdminByFid(user.getFcompanyid());

        /* String number = customLogService.selectFunmber("CT_DS_CARMAINTAIN", user.getFcompanyid());*/
        String fnumber = GetFnumber.fnumbers("WXTEST");

        //查询教练弹窗信息
        Map map1 = personController.getPageAsJl(request, "", "", "0");
        //车辆
        List<Car> cars = carService.queryCar(user.getFcompanyid());
        //部门
        List<Department> departmentList = departmentService.selectAdminListAsfcontid("", user.getFcompanyid());

        request.setAttribute("beginTime", TimeFormat.getMonth());
        request.setAttribute("endTime", TimeFormat.getNowTime());

        request.setAttribute("flag", "1");
        request.setAttribute("fbizdate", TimeFormat.getNowTime());
        request.setAttribute("createName", user.getName());
        request.setAttribute("fnumber", fnumber);
        request.setAttribute("department", department.getFnameL2());
        request.setAttribute("pb1", map1.get("pb"));
        request.setAttribute("persons", map1.get("sList"));
        request.setAttribute("time", TimeFormat.getNowTime());
        request.setAttribute("cars", cars);
        request.setAttribute("departmentList", departmentList);

        request.setAttribute("alertType", alertType);


        return "/backHome/carManagement/carmainTain/detailCarmainTain";

    }

    /**
     * @Author lcx
     * @Date 2018/2/7 0007 上午 9:20
     * 添加
     */
    @RequestMapping(value = "/add_Carmaintain")
    public String addCarmaintain(HttpServletRequest request, Carmaintain Carmaintain, @RequestParam(defaultValue = "0") String state, String auditstate) {

        //获取操作人信息
        User user = (User) request.getSession().getAttribute("user");
        //公司id
        Carmaintain.setCfficompanyid(user.getFcompanyid());
        //控制单元id
        Carmaintain.setFcontrolunitid(user.getFcompanyid());
        //获取当前修改时间
        String createTime = TimeFormat.timeFormat(new Date());
        //创建时间
        Carmaintain.setFcreatetime(createTime);
        //修改时间
        Carmaintain.setFcreatorid(user.getFid());

        //收集子类信息
        String[] cfmaintainitemid = request.getParameterValues("cfmaintainitemid");
        String[] cfmaintainitemName = request.getParameterValues("cfmaintainitemName");
        String[] cfrepairshopid = request.getParameterValues("cfrepairshopid");
        String[] cfmanhours = request.getParameterValues("cfmanhours");
        String[] cfbasemanhours = request.getParameterValues("cfbasemanhours");//合计工时
        String[] cfgsqty = request.getParameterValues("cfgsqty");
        String[] cfprice = request.getParameterValues("cfprice");
        String[] cfqty = request.getParameterValues("cfqty");
        String[] cfamount = request.getParameterValues("cfamount");//维修金额
        String[] cfallamount = request.getParameterValues("cfallamount");//合计
        String[] cfremark = request.getParameterValues("cfremark");


        //添加练车
        carmainTainService.addCarmaintain(state, Carmaintain, cfmaintainitemid, cfmaintainitemName, cfrepairshopid, cfmanhours, cfbasemanhours,
                cfgsqty, cfprice, cfqty, cfamount, cfallamount, cfremark, auditstate);


        //添加日志
        customLogService.addLog("车辆维修", TimeFormat.timeFormat(new Date()) + "对车辆维修新增", null, user.getFid());


        return "redirect:/DrivingSys/go_add_Carmaintain?alertType=bc";
    }

    @RequestMapping(value = "go_update_Carmaintain")
    public String goUpdateCarmaintain(HttpServletRequest request, String fid, String xqid) throws Exception {

        //获取操作人信息
        User user = (User) request.getSession().getAttribute("user");
        Department department = departmentService.queryAdminByFid(user.getFcompanyid());

        //查询教练弹窗信息
        Map map1 = personController.getPageAsJl(request, "", "", "0");
        //车辆
        List<Car> cars = carService.queryCar(user.getFcompanyid());
        //部门
        List<Department> departmentList = departmentService.selectAdminListAsfcontid("", user.getFcompanyid());

        Carmaintain carmaintain = carmainTainService.selectCarmainTainByFid(fid);

        if (carmaintain == null) {
            return "/error/not_data";
        }

        request.setAttribute("AuditState", carmainTainService.selectAuditPerson(carmaintain.getFnumber()));
        /*request.setAttribute("checkAuditState", carmainTainService.selectAuditPerson2(carmaintain.getFnumber()));*/
        request.setAttribute("activitiBPMN_KEY", ActivitiKey.Driving_GL_ID.equals(user.getFcompanyid())
                ? ActivitiKey.CLWX_KEY_GL
                : ActivitiKey.CLWX_KEY_NC);
        request.setAttribute("beginTime", TimeFormat.getMonth());
        request.setAttribute("endTime", TimeFormat.getNowTime());

        request.setAttribute("flag", "2");
        request.setAttribute("createName", user.getName());
        request.setAttribute("department", department.getFnameL2());
        request.setAttribute("pb1", map1.get("pb"));
        request.setAttribute("persons", map1.get("sList"));
        request.setAttribute("cars", cars);
        request.setAttribute("departmentList", departmentList);
        request.setAttribute("Carmaintain", carmaintain);

        return "/backHome/carManagement/carmainTain/detailCarmainTain";
    }


    @RequestMapping(value = "delete_Carmaintain")
    public String deleteCarmaintain(HttpServletRequest request, String[] deleteId, String[] fnumber) throws Exception {

        User user = (User) request.getSession().getAttribute("user");

        //测试先删除所有流程但是不删除这些单据
        carmainTainService.deleteByCarmainTainKey(deleteId, fnumber);

        //添加日志 暂时不添加流程
        customLogService.addLog("车辆管理", TimeFormat.timeFormat(new Date()) + "对车辆维修删除", null, user.getFid());


        return "redirect:/DrivingSys/queryCarmaintain/look.action?state=first";
    }

    @RequestMapping(value = "/update_Carmaintain")
    public String updateCarmaintain(HttpServletRequest request, Carmaintain carmaintain, String sum, String auditstate) {

        //获取操作人信息
        User user = (User) request.getSession().getAttribute("user");

        //获取当前修改时间
        String createTime = TimeFormat.timeFormat(new Date());
        //修改时间
        carmaintain.setFlastupdatetime(createTime);
        //修改人id
        carmaintain.setFlastupdateuserid(user.getFid());

        carmaintain.setSum(sum);

        addCarmaintain(request, carmaintain, "1", auditstate);

        customLogService.addLog("车辆管理", TimeFormat.timeFormat(new Date()) + "对车辆维修进行更新", null, user.getFid());

        return "redirect:/DrivingSys/queryCarmaintain/look.action?state=first&alertType=qd";
    }

    /**
     * @Author lcx
     * @Date 2017/12/15 0015 上午 11:55
     * ajax 查询部门
     */
    @RequestMapping(value = "/select_admin")
    @ResponseBody
    public List<Department> sellectAdminByName(HttpServletRequest request, @RequestParam(defaultValue = "", value = "name") String name) {
        User user = (User) request.getSession().getAttribute("user");
        return departmentService.selectAdminListAsfcontid(name, user.getFcompanyid());
    }

    //审核
    @RequestMapping(value = "/queryCarmaintainExamine")
    @ResponseBody
    public ServerResponse examine(HttpServletRequest request, @RequestParam(defaultValue = "", value = "fid") String fid,
                                  @RequestParam(defaultValue = "5", value = "state") String state,
                                  @RequestParam(defaultValue = "1", value = "agreed") String agreed,
                                  @RequestParam(defaultValue = "", value = "auditcomment") String auditcomment,
                                  @RequestParam(defaultValue = "", value = "AuditState") String AuditState,
                                  @RequestParam(defaultValue = "", value = "fnumber") String fnumber) {
        Carmaintain carmaintain = new Carmaintain();

        carmaintain.setFid(fid);
        carmaintain.setFnumber(fnumber);

        //设置反审核标识
        carmaintain.setAuditState(AuditState);

        return ServerResponse.createBySuccessMessage(carmainTainService.examine(carmaintain, state, agreed, auditcomment));
    }

    /**
     * @Author lcx
     * @Date 2018/3/1 0001 下午 2:19
     * 提交
     */
    @RequestMapping(value = "/queryCarmaintainSubmit")
    @ResponseBody
    public ServerResponse submit(HttpServletRequest request,
                                 @RequestParam(defaultValue = "", value = "fnumber") String fnumber,
                                 @RequestParam(defaultValue = "", value = "fid") String fid,
                                 @RequestParam(defaultValue = "", value = "cfdepartmentid") String Cfdepartmentid,
                                 @RequestParam(defaultValue = "", value = "sum") String sum,
                                 @RequestParam(defaultValue = "", value = "auditstate") String auditstate) {
        Carmaintain carmaintain = new Carmaintain();
        //获取操作人信息
        User user = (User) request.getSession().getAttribute("user");

        /*//获取当前修改时间
        String createTime = TimeFormat.timeFormat(new Date());
        //修改时间
        carmaintain.setFlastupdatetime(createTime);
        //修改人id
        carmaintain.setFauditorid(user.getFid());*/

        carmaintain.setFid(fid);
        carmaintain.setFnumber(fnumber);
        carmaintain.setCfdepartmentid(Cfdepartmentid);
        carmaintain.setSum(sum);

        carmainTainService.submit(carmaintain, auditstate);

        return ServerResponse.createBySuccessMessage("提交成功！");
    }

//    /**
//     * 导出
//     * @param request
//     * @param response
//     * @param jlName
//     * @param cfcoachno
//     * @param beginTime
//     * @param endTime
//     * @param departmentid
//     * @param cfmaintetype
//     * @return
//     */
//
//    @RequestMapping("/queryCarmaintainXls")
//    public String queryCarmaintainXls(HttpServletRequest request, HttpServletResponse response,
//                                      @RequestParam(defaultValue = "", value = "jlName") String jlName,
//                                      @RequestParam(defaultValue = "", value = "cfcoachno") String cfcoachno,
//                                      @RequestParam(defaultValue = "", value = "beginTime") String beginTime,
//                                      @RequestParam(defaultValue = "", value = "endTime") String endTime
//            , @RequestParam(value = "departmentid", defaultValue = "") String departmentid
//            , @RequestParam(value = "cfmaintetype", defaultValue = "") String cfmaintetype) {
//        //获取操作人信息
//        User user = (User) request.getSession().getAttribute("user");
//
//        //头部数据
//        List<Object> data = new ArrayList<>();
//
//        //尾部数据
//        List<Object> dataTail = new ArrayList<>();
//
//        List<String> tails = new ArrayList<>();
//
//        String head[] = {"业务日期", "车辆", "维修项目", "数量", "单价", "维修金额",
//                "工时数量", "工时", "工时金额", "合计", "部门"
//        };
//
//        Integer tail[] = {30000, 30000, 35000};
//
//        tails.add("1");
//        tails.add("2");
//        tails.add("3");
//
//        dataTail.add(tails);
//        //长度
//        Integer length[] = {5500, 4000, 6000, 2000, 2000, 2000, 2000, 2000, 2000, 2000,
//                3000};
//
//        String depName = "";
//
//        String[] ym = beginTime.split("-");
//
//        List<Carmaintain> carmaintainList = carmainTainService.selectCarmaintainXls(jlName, cfcoachno, beginTime, endTime, user.getFcompanyid(), departmentid, cfmaintetype);
//
//
//        for (Carmaintain carmaintain : carmaintainList) {
//            data.add(carmaintain.getFbizdate());
//            data.add(carmaintain.getCfcarName());
//            data.add(carmaintain.getCfmaintainitemName());//维修项目
//            data.add(carmaintain.getCfqty());//数量
//            data.add(carmaintain.getCfprice());//单价
//            data.add(carmaintain.getCfbasemanhours());//维修金额
//            data.add(carmaintain.getCfgsqty());//工时数量
//            data.add(carmaintain.getCfbasemanhours());//工时
//            data.add(carmaintain.getCfamount());//工时金额
//            data.add(carmaintain.getCfallamount());//合计
//            data.add(carmaintain.getCfdepartmentName());//部门
//    depName = carmaintain.getCfdepartmentName();
//}
//
//        try {
//                //导出Excel
//                if (ym.length > 2) {
//                //如果是事故维修 则打印事故维修报表
//                CommonExport.importExcel(response, ym[0] + "年" + ym[1] + "月" + "" + "汽车维修费用明细表（" + depName + "）.xls",
//                ym[0] + "年" + ym[1] + "月" + "" + "汽车维修费用明细表（" + depName + "）", data, head, length,tail,tails);
//
//                } else {
//                CommonExport.importExcel(response, "车辆维修" + TimeFormat.getNowTime2() + ".xls", "车辆维修", data, head, length);
//                }
//                } catch (Exception e) {
//                e.printStackTrace();
//                }
//
//                return "redirect:/DrivingSys/queryCarmaintain/look.action?state=first";
//                }

    /**
     * 批量打印
     * @param request
     * @param response
     * @param jlName
     * @param cfcoachno
     * @param beginTime
     * @param endTime
     * @param departmentid
     * @param cfmaintetype
     * @return
     */
    @RequestMapping("/queryCarmanBulkprint")
    public String queryCarmanBulkprint(HttpServletRequest request, HttpServletResponse response,
                                       @RequestParam(defaultValue = "", value = "jlName") String jlName,
                                       @RequestParam(defaultValue = "", value = "cfcoachno") String cfcoachno,
                                       @RequestParam(defaultValue = "", value = "beginTime") String beginTime,
                                       @RequestParam(defaultValue = "", value = "endTime") String endTime
            , @RequestParam(value = "departmentid", defaultValue = "") String departmentid
            , @RequestParam(value = "cfmaintetype", defaultValue = "") String cfmaintetype) throws Exception {
        PageBean<Carmaintain> pb = new PageBean<>();
        //获取操作人信息
        User user = (User) request.getSession().getAttribute("user");
        List<Carmaintain> carmaintainList = carmainTainService.selectCarmaintainXls(jlName, cfcoachno, beginTime, endTime, user.getFcompanyid());
        List<Carmaintain> carmaintainList2=new ArrayList<>();
        String nowfid="";
        String beginfid="";
        int i=0;
        List<String> countALL= new ArrayList<>();
        for(Carmaintain carmaintain:carmaintainList){
            Carmaintain carmaintain1=carmainTainService.selectCarmainTainByFid(carmaintain.getFid());
            nowfid=carmaintain.getFid();
            carmaintain1.setSum(i+"");
            if(!nowfid.equals(beginfid)){
            carmaintainList2.add(carmaintain1);
            i++;
            }
          beginfid=nowfid;
        }

        request.setAttribute("CarmaintainList",carmaintainList2);
        request.setAttribute("count",i);
    return "/backHome/carManagement/carmainTain/carmanBulkprint";
    }

    /**
     * 车辆事故维修导入
     * @param request
     * @param file
     * @return
     * @throws Exception
     */
    @RequestMapping("/importCarmainTainSG")
    @ResponseBody
    public Object importCarmainTainSG(HttpServletRequest request,@RequestParam(value = "file", required = false) MultipartFile file) throws Exception{

        String fileName = file.getOriginalFilename();
        // 获取文件后缀
        String prefix=fileName.substring(fileName.lastIndexOf("."));
        // 用uuid作为文件名，防止生成的临时文件重复
        String filesFileName=file.getOriginalFilename();
        //System.out.println("文件名字: "+request.getServletContext().getRealPath("/")+ "xls" + File.separatorChar + filesFileName);
        //读取
        final File excelFile = File.createTempFile(GetFid.UUIDIntoFid(), prefix);
        // MultipartFile to File
        file.transferTo(excelFile);

        //获取操作人信息
        User user = (User) request.getSession().getAttribute("user");

        //获取当前修改时间
        String createTime = TimeFormat.timeFormat(new Date());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String fbizDate=sdf.format(new Date());
//      导入结果
        int result=-1;
//        获取导入数据
     List<CarmaintainImport> carmaintainImports=poi.carmaintainImportMap(excelFile);
     //获取项目维修时间，并且进行分类
        if(carmaintainImports==null){
            return result;
        }else{
            //获取所有的项目日期
            String[] carmainDateAll=new String[carmaintainImports.size()];
            String[] carmainCarnameAll=new String[carmaintainImports.size()];
            String[] fixDepartment=new String[carmaintainImports.size()];
            int i =0;
            //赋值
            for(CarmaintainImport carmaintainImport: carmaintainImports){
                carmainDateAll[i]= carmaintainImport.getBusinessdate();
                carmainCarnameAll[i]= carmaintainImport.getCfcarName();
                fixDepartment[i]=carmaintainImport.getCfrepairshopName();
                i++;
            }
//          String [] carmainDate= toCasetrim(carmainDateAll);
              //生成一个list集合关于Camaintain
            List<Carmaintain> carmaintains=new ArrayList<>();
            int x=1;
            String [] newCarname=toCasetrim(carmainCarnameAll);
            for(int d=0;d<carmainDateAll.length;d++){

                //因为维修时间和维修车辆必须与下一行的不同才可以生成一个新的Camaintian

                if(!carmainCarnameAll[x].equals(carmainCarnameAll[x-1])||d==0){
                Carmaintain carmaintain=new Carmaintain();
                carmaintain.setFcreatorid(user.getFid()); //创建者id
                carmaintain.setCreateName(user.getName());//创建者
                carmaintain.setFcreatetime(createTime); //创建时间
                //公司id
                carmaintain.setCfficompanyid(user.getFcompanyid());
                //控制单元id
                carmaintain.setFcontrolunitid(user.getFcompanyid());
                //业务日期
                carmaintain.setFbizdate(carmainDateAll[x]);
                //车辆名称
                carmaintain.setCfcarName(carmainCarnameAll[x]);
                //获取修理厂名
                carmaintain.setCfdepartmentName(fixDepartment[x]);
                 List<Car> cars= carService.selectCarExcel(carmainCarnameAll[x],user.getFcompanyid());
                 //车辆的id
                    if(cars!=null&&cars.size()!=0){
                      carmaintain.setCfcarid(cars.get(0).getFid());
                    }else{
                        result=-3;
                      return  result;
                    }
                 //教练现在还无法获取
//                 carmaintain.setCfjiaolianid();
                carmaintains.add(carmaintain);
                  }
                if(x<carmainDateAll.length-1){
                    x++;
                }

            }

          result = carmainTainService.importCarmainTainSG(request,carmaintains,carmaintainImports,user,carmainDateAll,carmainCarnameAll);
        }
        //程序结束时，删除临时文件
        deleteFile(excelFile);
        return result;
    }




    private void deleteFile(File... files) {
        for (File file : files) {
            if (file.exists()) {
                file.delete();
            }
        }
    }
    /**
     * 数组去重
     * @return
     */
    public String[] toCasetrim(String [] oldString){
        String[] s = oldString;
        List list = Arrays.asList(s);
        Set set = new HashSet(list);
        String [] rid=(String [])set.toArray(new String[0]);
        return rid;
    }

    /**
     * @Author lcx
     * @Date 2018/6/19 0019 上午 9:49
     * 财务需求的 导出
     */
    @RequestMapping("/queryCarmaintainXlsAsCw")
    public String queryCarmaintainXlsAsCW(HttpServletRequest request, HttpServletResponse response,
                                      @RequestParam(defaultValue = "", value = "jlName") String jlName,
                                      @RequestParam(defaultValue = "", value = "cfcoachno") String cfcoachno,
                                      @RequestParam(defaultValue = "", value = "beginTime") String beginTime,
                                      @RequestParam(defaultValue = "", value = "endTime") String endTime
            , @RequestParam(value = "departmentid", defaultValue = "") String departmentid
            , @RequestParam(value = "cfmaintetype", defaultValue = "") String cfmaintetype) {
        //获取操作人信息
        User user = (User) request.getSession().getAttribute("user");

        //头部数据
        List<Object> data = new ArrayList<>();
        String head[] = {"单据编号", "业务日期", "备注", "审核人名称", "制单人名称", "部门", "维修类型", "教练", "修理厂", "单据状态",
                "维修项目", "工时数量", "工时", "单价", "数量", "工时金额", "维修金额", "车辆", "合计", "备注"
        };
        //长度
        Integer length[] = {8500, 5000, 6000, 3000, 3000, 3000, 3000, 3000, 10000, 3000,
                7000, 3000, 3000, 3000, 3000, 3000, 3000, 4000, 4000, 4000};

        List<Carmaintain> carmaintainList = carmainTainService.selectCarmaintainXls(jlName, cfcoachno, beginTime, endTime, user.getFcompanyid());


        for (Carmaintain carmaintain : carmaintainList) {
            data.add(carmaintain.getFnumber());
            data.add(carmaintain.getFbizdate());
            data.add(carmaintain.getFdescription());
            data.add(carmaintain.getCheckName());
            data.add(carmaintain.getCreateName());
            data.add(carmaintain.getCfdepartmentName());
            data.add(stateToString.cfdepartmentName(carmaintain.getCfmaintetype()));
            data.add(carmaintain.getJlName());
            data.add(carmaintain.getCfrepairshopName());//修理厂
            data.add(stateToString.billsState(carmaintain.getCfbillstate()));
            data.add(carmaintain.getCfmaintainitemName());//维修项目
            data.add(carmaintain.getCfgsqty());
            data.add(carmaintain.getCfbasemanhours());
            data.add(carmaintain.getCfprice());
            data.add(carmaintain.getCfqty());
            data.add(carmaintain.getCfamount());
            data.add(carmaintain.getCfbasemanhours());
            data.add(carmaintain.getCfcarName());
            data.add(carmaintain.getCfallamount());
            data.add(carmaintain.getCfremark());
        }

        try {
            //导出Excel
            CommonExport.importExcel(response, "车辆维修" + TimeFormat.getNowTime2() + ".xls", "车辆维修", data, head, length);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "redirect:/DrivingSys/queryCarmaintain/look.action?state=first";
    }

    /**
     * 测试导出
     * @param request
     * @param response
     * @param jlName
     * @param cfcoachno
     * @param beginTime
     * @param endTime
     * @param departmentid
     * @param cfmaintetype
     * @return
     */
    @RequestMapping("/queryCarmaintainXls")
    public String queryCarmaintainXlsst(HttpServletRequest request, HttpServletResponse response,
                                      @RequestParam(defaultValue = "", value = "jlName") String jlName,
                                      @RequestParam(defaultValue = "", value = "cfcoachno") String cfcoachno,
                                      @RequestParam(defaultValue = "", value = "beginTime") String beginTime,
                                      @RequestParam(defaultValue = "", value = "endTime") String endTime
            , @RequestParam(value = "departmentid", defaultValue = "") String departmentid
            , @RequestParam(value = "cfmaintetype", defaultValue = "") String cfmaintetype
            , @RequestParam(value = "repairshopid", defaultValue = "") String repairshopid) {
        //获取操作人信息
        User user = (User) request.getSession().getAttribute("user");

        //头部数据
        List<Object> data = new ArrayList<>();
        String depName = "";
        String[] ym = beginTime.split("-");
        List<Carmaintain> carmaintainList=new ArrayList<>();
        if("4".equals(cfmaintetype)){
        carmaintainList = carmainTainService.selectCarmaintainXls(jlName, cfcoachno,
                beginTime, endTime, user.getFcompanyid(), departmentid, "2", repairshopid);
        }else{
        carmaintainList = carmainTainService.selectCarmaintainXls(jlName, cfcoachno,
                beginTime, endTime, user.getFcompanyid(), departmentid, cfmaintetype, repairshopid);
        }
        String cfdepartment="";
        for (Carmaintain carmaintain : carmaintainList) {
            data.add(carmaintain.getFbizdate());
            data.add(carmaintain.getCfcarName());
            data.add(carmaintain.getCfmaintainitemName());//维修项目
            data.add(carmaintain.getCfqty());//数量
            data.add(carmaintain.getCfprice());//单价
            data.add(carmaintain.getCfamount());//维修金额
            data.add(carmaintain.getCfgsqty());//工时数量
            data.add(carmaintain.getCfmanhours());//工时
            data.add(carmaintain.getCfbasemanhours());//工时金额
            data.add(carmaintain.getCfallamount());//合计
            data.add(carmaintain.getCfdepartmentName());//部门
            cfdepartment=carmaintain.getCfdepartmentName();
            depName = carmaintain.getCfdepartmentName();
        }
        if (null==departmentid&&departmentid==""){
           cfdepartment="";
        }


        String head[] = {"业务日期", "车辆", "维修项目", "数量", "单价", "维修金额",
                "工时数量", "工时", "工时金额", "合计", "部门"
        };//5,8,9

        Integer tail[] = {30000, 30000, 35000};

        //长度
        Integer length[] = {5500, 4000, 6000, 2000, 2000, 2000, 2000, 2000, 2000, 2000,
                3000};
        //特定维修数据
        List<Object> dataNew = new ArrayList<>();

        //尾部数据
        List<String> tails = new ArrayList<>();

        //新表的字段头
        String headfor[] = {"业务日期", "报案号", "车号", "维修金额", "理赔金额","费用差额","理赔公司"
        };
        tails.add("制表:");
        tails.add("机务主管:");
        tails.add("财务主管:");
        tails.add("副校长:");
        tails.add("常务副校长:");

        //长度
        Integer lengthNew[] = {3000,4000, 3000, 2500, 2500,2500, 2400};

        //维修名称
        String fixType ="";
        if("1".equals(cfmaintetype)){
            fixType="正常维修";
        }else if("2".equals(cfmaintetype)){
            fixType = "事故维修";
        }else if("3".equals(cfmaintetype)){
            fixType = "公交车维修";
        }else if("4".equals(cfmaintetype)){
            fixType="事故维修";

        }
        //过滤日期和车辆类型
        //过滤日期和车辆类型
//        for(int i=0;i<carmaintainList.size();i++){
//                    if(i+1<carmaintainList.size()){
//
//
//                    String carName=carmaintainList.get(i).getCfcarName();
//                    String carNextName=carmaintainList.get(i+1).getCfcarName();
//                    String fbizdate=carmaintainList.get(i).getFbizdate();
//                    String fbizNextdate=carmaintainList.get(i+1).getFbizdate();
//                        if(carName.equals(carNextName)&&fbizdate.equals(fbizNextdate)){
//                                 carmaintainList.get(i+1).setCfallamount(carmaintainList.get(i).getCfallamount().add(carmaintainList.get(i+1).getCfallamount()));
//                                 carmaintainList.remove(i);
//                                 i--;
//                        }
//                }
//         }
        List<Carmaintain> newList=new ArrayList<>();
        for(Carmaintain carmaintain:carmaintainList){
            boolean flag=false;
            for(Carmaintain carmaintainNew: newList){
                if(carmaintain.getCfcarName()==null){
                    carmaintain.setCfcarName("该车辆未能查询到名称");
                }
                if(carmaintainNew.getCfcarName().equals(carmaintain.getCfcarName())){
                    carmaintainNew.setCfallamount(carmaintainNew.getCfallamount().add(carmaintain.getCfallamount()));
                    flag=true;
                }
            }
            if(!flag){
                newList.add(carmaintain);
            }

        }
        for (Carmaintain carmaintain : newList) {
            dataNew.add(carmaintain.getFbizdate());//业务日期
            dataNew.add("");//报案号
            dataNew.add(carmaintain.getCfcarName());//车号

            dataNew.add(carmaintain.getCfallamount());//维修金额  时间金额加上单价*数量的金额
            dataNew.add("");//理赔金额
            dataNew.add("");//费用差额
            dataNew.add("鼎和");//理赔公司
        }

        List<Object> dataSum= new ArrayList<>();

        if("2".equals(cfmaintetype)){
         dataSum=listForSum(dataNew,headfor,3,1);
        }else{

        dataSum=listForSum(data,head,5,1,8,2);
        }
        try {
            //导出Excel
            if (ym.length > 2) {
                if("2".equals(cfmaintetype)){
                //如果是事故维修 则打印事故维修报表
                CommonExport.importExcel(response, ym[0] + "年" + ym[1] + "月" + "" + fixType + "费用表"+".xls",
                        ym[0] + "年" + ym[1] + "月" + "" + fixType + "费用表-"+cfdepartment , dataNew, headfor, length,tail,tails,dataSum);
                }else if("1".equals(cfmaintetype)||"3".equals(cfmaintetype)||"4".equals(cfmaintetype)) {
                    CommonExport.importExcel(response, ym[0] + "年" + ym[1] + "月" + fixType + "费用表"+".xls",
                            ym[0] + "年" + ym[1] + "月" + "" + fixType + "费用表-"+cfdepartment, data, head, length,tail,tails,dataSum);
                }else{
                CommonExport.importExcelSum(response, ym[0] + "年" + ym[1] + "月" + "" + "汽车维修费用明细表（" + depName + "）.xls",
                        ym[0] + "年" + ym[1] + "月" + "" + "汽车维修费用明细表（" + depName + "）-"+cfdepartment, data, head, length,dataSum);
                }
            } else {
                CommonExport.importExcelSum(response, "车辆维修-"+cfdepartment+""+ TimeFormat.getNowTime2() + ".xls", "车辆维修", data, head, length,dataSum);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "redirect:/DrivingSys/queryCarmaintain/look.action?state=first";
    }

    /**
     *统计方法(完全相连)
     * @param list1 完成遍历的集合
     * @param head  表头
     * @param num   求和的第一个字段的下标
     * @param sum  需要增加多少个字段
     * @return
     */
    public List<Object> listForSum(List<Object> list1,String[] head,int num,int sum) {
        Double money = 0.00;
        List<Object> list = new ArrayList<>();
        DecimalFormat df = new DecimalFormat("#.00");
        list.add("合计：");
        for (int i = 0; i < num - 1; i++) {
            list.add(" ");
        }

        for (int i = 0; i < sum; i++) {

            for (int j = 0; j < list1.size() / head.length; j++) {

                if (list1.get(num + head.length * j) != null && !"".equals(list1.get(num + head.length * j))) {
                    money += Double.parseDouble(list1.get(num + head.length * j) + "");

                } else {
                    money += 0.00;
                }
            }
            if(money==0.00||money==null){
                list.add("0.00");
            }else{
                if(".00".equals(df.format(money))){
                    list.add("");
                }else{

                    list.add(df.format(money));
                }
            }
            num++;
            money = 0.00;
        }
        int listLength=head.length-list.size();
        for(int i=0;i<listLength;i++){

          list.add("");
        }

        return list;
    }

    /**
     *统计方法(完全相连)
     * @param list1 完成遍历的集合
     * @param head  表头
     * @param num   求和的第一个字段的下标
     * @param sum  需要增加多少个字段
     * @return
     */
    public List<Object> listForSum(List<Object> list1,String[] head,int num,int sum,int nextNum,int nextCount) {
        Double money = 0.00;
        List<Object> list = new ArrayList<>();
        DecimalFormat df = new DecimalFormat("#.00");
        list.add("合计：");
        for (int i = 0; i < num - 1; i++) {
            list.add(" ");
        }

        for (int i = 0; i < sum; i++) {

            for (int j = 0; j < list1.size() / head.length; j++) {

                if (list1.get(num + head.length * j) != null && !"".equals(list1.get(num + head.length * j))) {
                    money += Double.parseDouble(list1.get(num + head.length * j) + "");

                } else {
                    money += 0.00;
                }
            }
            if(money==0.00||money==null){
                list.add("0.00");
            }else{
                if(".00".equals(df.format(money))){
                    list.add("");
                }else{

                    list.add(df.format(money));
                }
            }
            num++;
            money = 0.00;
        }
        for(int i=0;i<nextNum-num;i++){
          list.add("");

        }

        for (int i = 0; i < nextCount; i++) {

            for (int j = 0; j < list1.size() / head.length; j++) {

                if (list1.get(nextNum + head.length * j) != null && !"".equals(list1.get(nextNum + head.length * j))) {
                    money += Double.parseDouble(list1.get(nextNum + head.length * j) + "");

                } else {
                    money += 0.00;
                }
            }
            if(money==0.00||money==null){
                list.add("0.00");
            }else{
                if(".00".equals(df.format(money))){
                    list.add("");
                }else{

                    list.add(df.format(money));
                }
            }
            nextNum++;
            money = 0.00;
        }

        int listLength=head.length-list.size();
        for(int i=0;i<listLength;i++){

            list.add("");
        }

        return list;
    }

}
